package cn.kgc.ubagnet.controller;

import cn.kgc.ubagnet.pojo.*;
import cn.kgc.ubagnet.service.buyer.BuyerService;
import cn.kgc.ubagnet.service.buyer.CrowdBuyerDetailService;
import cn.kgc.ubagnet.service.cart.CartService;
import cn.kgc.ubagnet.service.order.OrderDetailsService;
import cn.kgc.ubagnet.service.order.OrderService;
import cn.kgc.ubagnet.service.product.ProductService;
import com.github.pagehelper.PageInfo;
import org.springframework.data.relational.core.sql.In;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class OrderController {
    @Resource
    CartService cartService;
    @Resource
    ProductService proService;
    @Resource
    OrderService orderService;
    @Resource
    OrderDetailsService detailsService;
    @Resource
    BuyerService buyerService;

    @PostMapping("/order/add")
    @ResponseBody
    public int orderadd(@RequestBody  List<Integer> idlist){
        List<Integer> ids=new ArrayList<>();
        //记录
        int size=0;
        //生成随机订单号
        String str="0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<16;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        System.out.println(sb);
        for (int i=0;i<idlist.size()-1;i++){
            //ids，用来删除
            ids.add(idlist.get(i));
            //先查询购物车
            Cart cart=cartService.CartByid(idlist.get(i));
            //将购物车信息添加到订单
            Order order=new Order();
         /*   order.setIscoupon(0);
            order.setClothesid(cart.getProid());
            order.setCount(cart.getNum());
            order.setIsfreight(1);
            order.setOrderdetailsid(sb.toString());
            order.setRealitypay(cart.getPrice()*cart.getNum());
            order.setStatus(1);*/
            //添加
            int result=orderService.Ordersave(order);
            if(result>0){//如果添加成功，就把记录+1
                size++;
            }
            System.out.println(ids);
        }
        if(size==ids.size()){//如果添加成功的次数等于ids的长度,就把已经添加的数据从cart中删除
//            cartService.delCart(ids);
        }
        System.out.println(idlist);
        return 1;
    } //显示购物车

    @GetMapping("/order/list")
    @ResponseBody
    public List<OrderProImgDetailAddress> orderlist(HttpSession session){
        Long detailid= (Long) session.getAttribute("orderdetailid");
        List<OrderProImgDetailAddress> list=orderService.OrderListBydetailid(detailid);
//        System.out.println(list);
          return list;
    }

    @Resource
    BuyerService ouyerService;

    @GetMapping("/myorder/list")
    @ResponseBody
    public PageInfo<OrderProImgDetailAddress> myorderlist(@RequestParam(value = "status",required = false,defaultValue = "0") Integer status,
                                                          @RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum,
                                                          @RequestParam(value = "pageSize",required = false,defaultValue = "4") Integer pageSize,
                                                          HttpSession session){

        //获取用户id
        Integer userid=ouyerService.seleByPhone(CrowdBuyerDetailService.phone).getUserid();
        PageInfo<OrderProImgDetailAddress> pageInfo=orderService.OrderPageInfoBytype(userid,status,pageNum,pageSize);
        System.out.println(status);
        return pageInfo;
    }

    //订单详细信息存储编号session
    @GetMapping("/session/orderdetailid")
    @ResponseBody
    public String session_orderdetailid(Long orderdetailid,HttpSession session){
        session.setAttribute("orderdetailid",orderdetailid);
        return orderdetailid.toString();
    }
    //订单详细信息存储编号session 2
    @GetMapping("/session/detailid")
    @ResponseBody
    public String session_detailid(Long detailid,HttpSession session){
        session.setAttribute("detailid",detailid);
        return null;
    }
    //订单列表去详细页面显示
    @GetMapping("/detail/list")
    @ResponseBody
    public List<OrderProImgDetailAddress> detaillist(HttpSession session){
        Long detailid= (Long) session.getAttribute("detailid");
        List<OrderProImgDetailAddress> list=orderService.OrderListBydetailid(detailid);
//        System.out.println(list);
        return list;
    }

    //余额支付下单
    @PostMapping("/order/balpay")
    @ResponseBody
    public Map<String,Object> balpay(@RequestBody List<Integer> idlist){
        Map<String,Object> map=new HashMap<>();
        //获取用户数据
        Buyer user=buyerService.seleByPhone(CrowdBuyerDetailService.phone);
        //获取地址编号
        String addressid=idlist.get(0).toString();

        //id集合
        List<Integer> ids=new ArrayList<>();
        //总价钱
        Double countprice=0.0;
        //订单详细编号
        Long orderdetailsid=null;
        for (int i=1;i<idlist.size();i++){
            ids.add(idlist.get(i));
            //查询订单
            Order order=orderService.OrderById(idlist.get(i));
            //总价钱计算
            countprice=countprice+order.getTotalprice();
            //详细订单号
            orderdetailsid=order.getOrderdetailsid();
            //将状态修改
            order.setStatus(2);//待发货
            //修改订单信息
           int oresult=orderService.Ordersave(order);
            if(oresult<0){//修改失败
                map.put("msg","no");
                return map;
            }

            //查询商品信息
            Product product=proService.getProById(order.getClothesid());
            product.setStock(product.getStock()-order.getCount());
            //修改商品数量
           int presult=proService.ProUpdate(product);
           if(presult<0){//修改失败
               map.put("msg","no");
               return map;
           }
//            System.out.println(ids);
        }
        //查询订单详细状态
        Orderdetails od=detailsService.Query_OD(orderdetailsid);
        od.setAddressid(addressid);
        od.setRealitypay(countprice);
        od.setPaydate(new Date());
        od.setChengjiaodate(new Date());
        //修改订单详细信息
        int result=detailsService.Update_OD(od);
        if(result<0){//修改失败
            map.put("msg","no");
            return map;
        }
        //修改用户余额
        user.setBalance(user.getBalance()-countprice);
        int uresult=buyerService.upBuyer(user);
        if(uresult<0){//修改失败
            map.put("msg","no");
            return map;
        }
            map.put("msg","yes");
        return map;
    }
}
